#include "UDPSender.h"
//#include "MainWindow.h"
#include "ConfigManager.h"

UDPSender::UDPSender()
{
}

void UDPSender::Initialize()
{
	start();
}

void UDPSender::run()
{
	UDPPacket *packet;
//	QByteArray packet;
	bool full;
	while (true)
	{
		if (!_sendQueue.isEmpty())
		{
			full = false;
			while (!full && !_sendQueue.isEmpty())
			{
				packet = _sendQueue.first();
				if (_socket.writeDatagram(packet->dgram, packet->addr, packet->port) == -1)
					full = true;
				else
				{
					delete packet;
					_sendQueue.dequeue();
				}
			}
		}
		sleep(1);
	}
}

void UDPSender::Enqueue(QByteArray packet, QHostAddress addr, int port)
{
//	_mutex.lock();
	UDPPacket *insertPacket = new UDPPacket;
	if (insertPacket != NULL)
	{
		_mutex.lock();
		insertPacket->dgram = packet;
		insertPacket->addr = addr;
		insertPacket->port = port;
		_sendQueue.enqueue(insertPacket);
		_mutex.unlock();
	}
}

void UDPSender::SendDatagram(QByteArray packet)
{
	SendDatagram(packet, CONFIG_MANAGER->GetNetworkPort());
}

void UDPSender::SendDatagram(QByteArray packet, int port)
{
	for (int j = 0; j < 3; j++)
	{
		if (!CONFIG_MANAGER->GetBroadcastAddress().isNull() &&
			_socket.writeDatagram(packet, CONFIG_MANAGER->GetBroadcastAddress(), port) == -1)
		{
			Enqueue(packet, CONFIG_MANAGER->GetBroadcastAddress(), port);
		}
		for (int i = 0; i < 4; i++)
		{
			if (CONFIG_MANAGER->GetNetworkAddr(i).isSet &&
				!CONFIG_MANAGER->GetNetworkAddr(i).addr.isNull() &&
				_socket.writeDatagram(packet, CONFIG_MANAGER->GetNetworkAddr(i).addr, port) == -1)
			{
				Enqueue(packet, CONFIG_MANAGER->GetNetworkAddr(i).addr, port);
			}
		}
		//ip_addr config..
		for (int i = 0; i < CONFIG_MANAGER->GetIPNamesCount(); i++)
		{
			if (!CONFIG_MANAGER->GetIPNameAddress(i).isNull() &&
				_socket.writeDatagram(packet, CONFIG_MANAGER->GetIPNameAddress(i), port) == -1)
			{
				Enqueue(packet, CONFIG_MANAGER->GetIPNameAddress(i), port);
			}
		}
	}
}

void UDPSender::SendDatagram(QByteArray packet, QHostAddress addr, int port)
{
	for(int j = 0; j < 3; j++)
	{
		if (_socket.writeDatagram(packet, addr, port) == -1)
			Enqueue(packet, addr, port);
	}
}
